#pragma once 
#include <iostream>
#include <string>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

namespace ns_tcpserver {
    const int backlog = 5;

    class TcpServer {
        private:
            uint16_t port;
            int listen_sock;
        public:
            TcpServer(uint16_t _port)
                :port(_port)
                ,listen_sock(-1)
            {}
            void InitTcpServer() {
                listen_sock = socket(AF_INET, SOCK_STREAM, 0);
                if (listen_sock < 0) {
                    std::cerr << "listen_socket error" << std::endl;
                    exit(2);
                }
                struct sockaddr_in local;
                bzero(&local, sizeof(local));
                local.sin_family = AF_INET;
                local.sin_port = htons(port);
                local.sin_addr.s_addr = htonl(INADDR_ANY); 
                if (bind(listen_sock, (struct sockaddr*)&local, sizeof(local)) <  0) {
                    std::cerr << "bind error" << std::endl;
                    exit(3);
                }
                // 3、监听套接字，tcp是面向连接的，正式传递数据之前需要先建立连接
                if (listen(listen_sock, backlog) < 0) {
                    std::cerr << "listen error" << std::endl;
                    exit(4);
                }        
            }
            void Loop() {
                while (true) {
                    //1、获取连接、
                    struct sockaddr_in peer;
                    socklen_t len = sizeof(peer);
                    int sock = accept(listen_sock, (struct sockaddr*)&peer, &len); //输入输出参数
                    if (sock < 0) {
                        std::cerr << "warning : accept error" << std::endl;
                        continue;
                    }
                    // 使用socket通信
                }
            }
            ~TcpServer() {
                if (listen_sock > 0) {
                    close(listen_sock);
                }
            }
    };
}

